/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJDialog.java
 *
 * Created on May 9, 2010, 1:51:02 PM
 */
package fileman;

import Global.Data;
import Global.UserPrefs;
import NodeManager.Node;
import NodeManager.NodeManagerService;
import NodeManager.RdfModelManager;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;

/**
 *
 * @author Conor
 */
public class NodeChooserDialog extends javax.swing.JDialog {

    /** Creates new form NewJDialog */
    public NodeChooserDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        Global.UserPrefs prefs = new UserPrefs();

        Data.NodesDirectory = prefs.GetPreference("NodesDir", "");
        lblNodesDir.setText(Data.NodesDirectory);

        Data.Node1Path = prefs.GetPreference(Data.Node1Name, "");
        lblNode1.setText(Data.Node1Path);

        Data.Node2Path = prefs.GetPreference(Data.Node2Name, "");
        lblNode2.setText(Data.Node2Path);

        Data.Node3Path = prefs.GetPreference(Data.Node3Name, "");
        lblNode3.setText(Data.Node3Path);

        this.fileManager = (MainGUI) parent;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        lblNode2 = new javax.swing.JLabel();
        lblNode3 = new javax.swing.JLabel();
        lblNode1 = new javax.swing.JLabel();
        cmdNode1 = new javax.swing.JButton();
        lblNodesDir = new javax.swing.JLabel();
        cmdSelectDir = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        cmdSelectRdf = new javax.swing.JButton();
        lblRdfFile = new javax.swing.JLabel();
        cmdCancel = new javax.swing.JButton();
        cmdContinue = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(fileman.FilemanApp.class).getContext().getResourceMap(NodeChooserDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setName("jPanel1"); // NOI18N

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        lblNode2.setText(resourceMap.getString("lblNode2.text")); // NOI18N
        lblNode2.setName("lblNode2"); // NOI18N

        lblNode3.setText(resourceMap.getString("lblNode3.text")); // NOI18N
        lblNode3.setName("lblNode3"); // NOI18N

        lblNode1.setText(resourceMap.getString("lblNode1.text")); // NOI18N
        lblNode1.setName("lblNode1"); // NOI18N

        cmdNode1.setText(resourceMap.getString("cmdNode1.text")); // NOI18N
        cmdNode1.setName("cmdNode1"); // NOI18N
        cmdNode1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdNode1ActionPerformed(evt);
            }
        });

        lblNodesDir.setText(resourceMap.getString("lblNodesDir.text")); // NOI18N
        lblNodesDir.setName("lblNodesDir"); // NOI18N

        cmdSelectDir.setText(resourceMap.getString("cmdSelectDir.text")); // NOI18N
        cmdSelectDir.setName("cmdSelectDir"); // NOI18N
        cmdSelectDir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdSelectDirActionPerformed(evt);
            }
        });

        jButton5.setText(resourceMap.getString("jButton5.text")); // NOI18N
        jButton5.setName("jButton5"); // NOI18N
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(fileman.FilemanApp.class).getContext().getActionMap(NodeChooserDialog.class, this);
        cmdSelectRdf.setAction(actionMap.get("cmdRdfFileActionPerformed")); // NOI18N
        cmdSelectRdf.setText(resourceMap.getString("cmdSelectRdf.text")); // NOI18N
        cmdSelectRdf.setName("cmdSelectRdf"); // NOI18N

        lblRdfFile.setText(resourceMap.getString("lblRdfFile.text")); // NOI18N
        lblRdfFile.setName("lblRdfFile"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                    .addComponent(cmdSelectRdf, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmdSelectDir, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                    .addComponent(cmdNode1, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblRdfFile, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(lblNodesDir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblNode1, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE))
                    .addComponent(lblNode2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
                    .addComponent(lblNode3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdSelectDir)
                    .addComponent(lblNodesDir))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdNode1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblNode1))
                .addGap(12, 12, 12)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblNode2))
                .addGap(12, 12, 12)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblNode3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdSelectRdf)
                    .addComponent(lblRdfFile, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        cmdCancel.setText(resourceMap.getString("cmdCancel.text")); // NOI18N
        cmdCancel.setName("cmdCancel"); // NOI18N
        cmdCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCancelActionPerformed(evt);
            }
        });

        cmdContinue.setText(resourceMap.getString("cmdContinue.text")); // NOI18N
        cmdContinue.setName("cmdContinue"); // NOI18N
        cmdContinue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdContinueActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(236, Short.MAX_VALUE)
                .addComponent(cmdContinue)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmdCancel)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdCancel)
                    .addComponent(cmdContinue))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-406)/2, (screenSize.height-301)/2, 406, 301);
    }// </editor-fold>//GEN-END:initComponents

    @Override
    protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            cancelled = true;
        }
    }

    private void cmdContinueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdContinueActionPerformed
        // TODO add your handling code here:
        if (this.isNodeTaken("")) {
            JOptionPane.showMessageDialog(NodeChooserDialog.this,
                    "All nodes have to be set before proceeding",
                    "Warning",
                    JOptionPane.WARNING_MESSAGE);

        } else {

            Global.UserPrefs prefs = new UserPrefs();
            prefs.SavePreference("NodesDir", lblNodesDir.getText());
            prefs.SavePreference(Data.Node1Name, lblNode1.getText());
            prefs.SavePreference(Data.Node2Name, lblNode2.getText());
            prefs.SavePreference(Data.Node3Name, lblNode3.getText());

            this.initNodeManager();
            this.dispose();
        }
}//GEN-LAST:event_cmdContinueActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        //Set up the file chooser.
        chooseNode(3);
}//GEN-LAST:event_jButton5ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        //Set up the file chooser.
        chooseNode(2);
}//GEN-LAST:event_jButton2ActionPerformed

    private void cmdNode1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdNode1ActionPerformed
        //Set up the file chooser.
        chooseNode(1);
}//GEN-LAST:event_cmdNode1ActionPerformed

    private void cmdCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCancelActionPerformed
        // TODO add your handling code here:
        cancelled = true;
        dispose();
    }//GEN-LAST:event_cmdCancelActionPerformed

    private void cmdSelectDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSelectDirActionPerformed
        // TODO add your handling code here:
        //Set up the file chooser.
        if (jFileChooser1 == null) {
            jFileChooser1 = new JFileChooser();

            //Add a custom file filter and disable the default
            //(Accept All) file filter.

            jFileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        }

        //Show it.
        int returnVal = jFileChooser1.showDialog(NodeChooserDialog.this,
                "Select");

        //Process the results.
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();

            if (!this.isNodeTaken(file.getPath())) {

                Data.NodesDirectory = file.getPath();
                this.lblNodesDir.setText(Data.NodesDirectory);
            } else {
                JOptionPane.showMessageDialog(NodeChooserDialog.this,
                        "The location is already used",
                        "Node Selection Warning",
                        JOptionPane.WARNING_MESSAGE);
            }

        } else {
            System.out.println("Operation cancelled by user.");
        }

        //Reset the file chooser for the next time it's shown.
        jFileChooser1.setSelectedFile(null);


    }//GEN-LAST:event_cmdSelectDirActionPerformed

    private void chooseNode(int node) {

        //Set up the file chooser.
        if (jFileChooser1 == null) {
            jFileChooser1 = new JFileChooser();

            //Add a custom file filter and disable the default
            //(Accept All) file filter.

            jFileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        }

        //Show it.
        int returnVal = jFileChooser1.showDialog(NodeChooserDialog.this,
                "Select");

        //Process the results.
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();

            if (!this.isNodeTaken(file.getPath())) {

                switch (node) {
                    case 1: {
                        Data.Node1Path = file.getPath();
                        this.lblNode1.setText(Data.Node1Path);
                        break;
                    }
                    case 2: {
                        Data.Node2Path = file.getPath();
                        this.lblNode2.setText(Data.Node2Path);
                        break;
                    }
                    case 3: {
                        Data.Node3Path = file.getPath();
                        this.lblNode3.setText(Data.Node3Path);
                        break;
                    }
                }

            } else {
                JOptionPane.showMessageDialog(NodeChooserDialog.this,
                        "The location is already used",
                        "Node Selection Warning",
                        JOptionPane.WARNING_MESSAGE);
            }

        } else {
            System.out.println("Operation cancelled by user.");
        }

        //Reset the file chooser for the next time it's shown.
        jFileChooser1.setSelectedFile(null);

    }

    private boolean isNodeTaken(String nodePath) {
        boolean nodeTaken = false;

        if (nodePath.equalsIgnoreCase(Data.Node1Path)) {
            nodeTaken = true;
        }

        if (nodePath.equalsIgnoreCase(Data.Node2Path)) {
            nodeTaken = true;
        }

        if (nodePath.equalsIgnoreCase(Data.Node3Path)) {
            nodeTaken = true;
        }

        if (nodePath.equalsIgnoreCase(Data.NodesDirectory)) {
            nodeTaken = true;
        }

        return nodeTaken;

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                NodeChooserDialog dialog = new NodeChooserDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    public boolean isCancelled() {
        return cancelled;
    }

    private void initNodeManager() {

        try {
            if (rdfFile == null) {
                rdfFile = new File(Data.NodesDirectory + File.separatorChar + Data.DefaultRdfFileName);
            }

            if (rdfFile == null || !rdfFile.exists()) {
                Node node1 = new Node(Global.Data.Node1Name, Global.Data.Node1Path);
                Node node2 = new Node(Global.Data.Node2Name, Global.Data.Node2Path);
                Node node3 = new Node(Global.Data.Node3Name, Global.Data.Node3Path);

                fileManager._rdfModelManager = new RdfModelManager(node1, node2, node3);
            } else {
                fileManager._rdfModelManager = new RdfModelManager(rdfFile);
            }
        } catch (Exception ex) {
            System.out.println("Error: Creating RdfModelManager failed!");
        }

        fileManager._nodeManagerService = new NodeManagerService(fileManager._rdfModelManager, fileManager);
        fileManager._nodeManagerService.start();

    }

    @Action
    public void cmdRdfFileActionPerformed() {

                // TODO add your handling code here:
        //Set up the file chooser.
        if (jFileChooser2 == null) {
            jFileChooser2 = new JFileChooser();

	    //Add a custom file filter and disable the default

            jFileChooser2.setFileSelectionMode(JFileChooser.FILES_ONLY);
            jFileChooser2.addChoosableFileFilter(new RdfFileFilter());
        }

        //Show it.
        int returnVal = jFileChooser2.showDialog(NodeChooserDialog.this,
                                      "Select");

        //Process the results.
        if (returnVal == JFileChooser.APPROVE_OPTION) {

            this.rdfFile = jFileChooser2.getSelectedFile();
            this.lblRdfFile.setText(rdfFile.getPath());

        } else {
            System.out.println("Operation cancelled by user.");
        }

        //Reset the file chooser for the next time it's shown.
        jFileChooser2.setSelectedFile(null);
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdCancel;
    private javax.swing.JButton cmdContinue;
    private javax.swing.JButton cmdNode1;
    private javax.swing.JButton cmdSelectDir;
    private javax.swing.JButton cmdSelectRdf;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblNode1;
    private javax.swing.JLabel lblNode2;
    private javax.swing.JLabel lblNode3;
    private javax.swing.JLabel lblNodesDir;
    private javax.swing.JLabel lblRdfFile;
    // End of variables declaration//GEN-END:variables
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JFileChooser jFileChooser2;
    private boolean cancelled = false;
    private MainGUI fileManager;
    private File rdfFile;
}
